package com.wedding.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义spring security filter,需要在security配置文件里配置一下
 */
public class ImageCodeFilter extends OncePerRequestFilter {
    private  final Logger logger = LoggerFactory.getLogger(ImageCodeFilter.class);
    private MyAuthenticFailHandler authenticFailHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //判断是否是登录请求
        if(request.getRequestURI().contains("/userLogin")){
            try{
                //校验验证码 获取验证码
                final String imageCode = request.getParameter("imageCode").toUpperCase();
                logger.debug(imageCode+"===========");
                String verifyCodeExpected = (String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
                logger.debug(verifyCodeExpected+"===========");
                if(!imageCode.equals(verifyCodeExpected)){
                    throw new ImageCodeException("验证码不一致");
                }
            }catch(AuthenticationException e){
                //交给权限失败处理器
                authenticFailHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }

    public void setAuthenticFailHandler(MyAuthenticFailHandler authenticFailHandler) {
        this.authenticFailHandler = authenticFailHandler;
    }
}
